using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace Home.Site.Models.DataLayer
{ 
    public class PhotoAlbumRepository : IPhotoAlbumRepository
    {
        readonly PromikeDBEntities context = new PromikeDBEntities();

        public IQueryable<PhotoAlbum> All
        {
            get { return context.PhotoAlbums; }
        }

        public IQueryable<PhotoAlbum> AllIncluding(params Expression<Func<PhotoAlbum, object>>[] includeProperties)
        {
            IQueryable<PhotoAlbum> query = context.PhotoAlbums;
            foreach (var includeProperty in includeProperties) {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public PhotoAlbum Find(int id)
        {
            return context.PhotoAlbums.Find(id);
        }

        public void InsertOrUpdate(PhotoAlbum photoalbum)
        {
            if (photoalbum.idalbum == default(int)) {
                // New entity
                context.PhotoAlbums.Add(photoalbum);
            } else {
                // Existing entity
                context.Entry(photoalbum).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var photoalbum = context.PhotoAlbums.Find(id);
            context.PhotoAlbums.Remove(photoalbum);
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public int? LastAlbumId()
        {
            var last = context.PhotoAlbums.OrderByDescending(x=>x.idalbum).ToArray()[0];
            if (last != null) return last.idalbum;
            return null;
        }

        public IQueryable<PhotoAlbum> GetAlbums()
        {
            return context.PhotoAlbums;
        }

        public PhotoAlbum LastAlbum()
        {
            return context.PhotoAlbums.Where(a => a.Show).OrderByDescending(x => x.idalbum).FirstOrDefault();            
        }

        public IQueryable<PhotoAlbum> GetPhotoAlbumsByUser(string userName)
        {
            return context.PhotoAlbums.Where(a=>a.Author == userName).OrderByDescending(x=>x.idalbum);
        }

        public void Dispose() 
        {
            context.Dispose();
        }
    }
}